package com.wyf.test.view

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.v4.app.FragmentActivity
import android.util.Log
import android.widget.Button
import android.widget.RelativeLayout
import android.widget.Toast

import com.squareup.okhttp.Callback
import com.squareup.okhttp.MediaType
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request
import com.squareup.okhttp.RequestBody
import com.squareup.okhttp.Response
import com.wyf.test.widget.LoadCircleView
import com.wyf.test.R
import com.wyf.test.bean.Student
import com.wyf.test.widget.VoiceSinWaveView

import org.json.JSONException
import org.json.JSONObject

import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.text.SimpleDateFormat
import java.util.Date
import java.util.concurrent.TimeUnit

/**
 * 主页面
 */
class MainActivity : FragmentActivity(), VoiceSinWaveView.VoiceWaveCallBack {
    private var test: Button? = null
    private var mContext: Context? = null

    private val handler = Handler()

    private var running: Runnable? = null
    internal var i = 0

    private val TAG = javaClass.simpleName

    internal var text = "{\"busyTypes\":[\"1010\",\"呵呵呵++呵呵呵\"],\"cachemax\":\"10\",\"collectperiod\":\"0\"}"

    var students:ArrayList<Student>?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initView()
        students = ArrayList()
        for(i in 0..20){
            var student = Student("xy",20+i,"m")
            students!!.add(student)
        }
        println(students.toString())
        for (i in students!!.indices){
            println(students!!.get(i))
        }
        for (s in students!!.iterator()) {
            println("=="+s)
        }
        students!!.map {when(it.age){
            20 -> println(it)
            21 -> println(it.name)
        } }

    }

    private fun shutSend() {
        if (running != null) {
            handler.removeCallbacks(running)
            running = null
        }
    }

    private fun startSend() {
        if (running == null) {
            Log.d("============", "is null ")
            running = object : Runnable {
                override fun run() {
                    handler.postDelayed(this, 50)//设置延迟时间
                    //                    sendData();
//                    sendMessage()
                    sendHttpMessage();
                }
            }
            handler.postDelayed(running, 50)//延迟调用
        }
    }


    private fun sendData() {
        val intent = Intent()
        intent.putExtra("TIME", getTime(System.currentTimeMillis()))
        intent.putExtra("APPID", "0204")
        intent.putExtra("BUSIID", "02")
        intent.putExtra("CONTENT", "知青 01;电视剧;剧情;20160704235817;0-1;电视剧;剧情电视剧;剧情电视剧;")
        intent.action = "com.guoantvbox.dataacquire.service"
        startService(intent)
    }

    /**
     * 时间戳转换时间

     * @param
     * *
     * @return
     */
    fun getTime(t: Long): String {
        var time = ""
        val formatter = SimpleDateFormat("yyyyMMddHHmmss")
        val date = Date(t)
        time = formatter.format(date)
        return time
    }

    private var mLoadCircleView: LoadCircleView? = null
    private var mVoiceSinWaveView: VoiceSinWaveView? = null
    private var topRelativeLayout: RelativeLayout? = null
    private var viewById: Button? = null

    private var isStart = false

    private fun initView() {
        test = findViewById(R.id.test) as Button
        mContext = this@MainActivity
        topRelativeLayout = findViewById(R.id.top) as RelativeLayout
        mVoiceSinWaveView = VoiceSinWaveView(mContext)
        mVoiceSinWaveView!!.setCallBack(this)
        mLoadCircleView = LoadCircleView(mContext, 70f,
                mContext!!.resources.getColor(R.color.duer_voice_primary_start))
        topRelativeLayout!!.addView(mLoadCircleView)
        mVoiceSinWaveView!!.showInParentView(topRelativeLayout)
        mVoiceSinWaveView!!.start()
        mVoiceSinWaveView!!.changeVolume(40f)
        viewById = findViewById(R.id.send) as Button

        viewById!!.setOnClickListener {
            if (!isStart) {
                isStart = true
                startSend()
                viewById!!.text = "停止"
            } else {
                isStart = false
                shutSend()
                viewById!!.text = "开始"
            }
        }

        mClient = OkHttpClient()
        mClient!!.setConnectTimeout(3, TimeUnit.SECONDS)
        mClient!!.setReadTimeout(10, TimeUnit.SECONDS)

        test!!.setOnClickListener {
            //                sendMessage();

            sendHttpMessage()

            //                int x=(int)(Math.random()*100);
            //                mVoiceSinWaveView.changeVolume(x);
            //                mVoiceSinWaveView.removeFromParent();
            //                mLoadCircleView.setMaskColor(mContext.getResources().getColor(R.color.colorPrimary));
            //                mLoadCircleView.begin();
        }
    }

    private var mClient: OkHttpClient? = null

    private fun sendHttpMessage() {
        val message = JSONObject()
        try {
            message.put("systemTypeNo", "3")
            message.put("businessTypeNo", "2")
            message.put("recordTime", (System.currentTimeMillis() / 1000).toString() + "")
            try {
                message.put("data", URLEncoder.encode(text, "UTF-8") + "")
            } catch (e: UnsupportedEncodingException) {
                e.printStackTrace()
            }

        } catch (e: JSONException) {
            e.printStackTrace()
        }

        Log.d(TAG, "sendHttpMessage: " + message.toString())
        val url = "http://127.0.0.1:1894/datacollection"
        val request = Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                message.toString())).build()
        mClient!!.newCall(request).enqueue(object : Callback {
            override fun onFailure(request: Request, e: IOException) {
                Log.d(TAG, "onFailure: ============" + e.toString())
            }

            @Throws(IOException::class)
            override fun onResponse(response: Response) {
                Log.d(TAG, String(response.body().bytes()) + "====onResponse: ==================" + response.code())
            }
        })

    }

    private fun sendMessage() {
        val intent = Intent()
        //        ComponentName componentName = new ComponentName("com.bupt.datacollectionservice",
        //                "com.bupt.datacollectionservice.service.CommandService");
        //        intent.setComponent(componentName);
        intent.`package` = "com.bupt.datacollectionservice"
        intent.action = "com.guoantvbox.dataacquire.service"
        intent.putExtra("systemTypeNo", "3")
        intent.putExtra("businessTypeNo", "2")
        intent.putExtra("recordTime", (System.currentTimeMillis() / 1000).toString() + "")
        intent.putExtra("data", text)
        startService(intent)
        i++
        Toast.makeText(this@MainActivity, "发送  " + i, Toast.LENGTH_SHORT).show()
    }

    override fun fadeToQuarter() {

    }

    override fun fadeOut() {

    }
}
